package com.zhang.handler;

import com.zhang.ChannelManage;
import com.zhang.common.Constant;
import com.zhang.common.config.GlobalConfig;
import com.zhang.common.message.ProxyMessage;
import com.zhang.common.message.ProxyMessageUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 客户端注册ngrok服务端 handler
 * @author 98265
 */
public class RegisterHandler extends ChannelInboundHandlerAdapter {
    /**
     * 日志对象
     */
    static private Logger log = LoggerFactory.getLogger(RegisterHandler.class);

    static private  String proxyServer = GlobalConfig.props.getStr("subdomain") + "." + GlobalConfig.props.getStr("serverdomain");
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端往服务端注册");

        ProxyMessage proxyMessage = ProxyMessageUtil.buildRegisterReq(proxyServer);
        ctx.writeAndFlush(proxyMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ProxyMessage proxyMessage = (ProxyMessage) msg;
        if (proxyMessage.getMsgType() == Constant.MessageType.TYPE_REGISTER_RESPONSE_SUCCESS){
            log.debug("注册成功");
            Integer port = proxyMessage.getPort();
            log.info("访问的路径是 {}:{}",proxyServer,port);
            ctx.channel().attr(Constant.HTTP_PORT).set(port);
            //代理服务器存储
            ChannelManage.setNgrokServerChannel(ctx.channel());
        }else if(proxyMessage.getMsgType() == Constant.MessageType.TYPE_REGISTER_RESPONSE_FAIL){
            log.error("{} 注册失败",proxyMessage);
            ctx.close();
            return;
        }else{
            ctx.fireChannelRead(msg);
        }
    }

}
